<template>
    <div>
        <el-form :model="formData" label-width="150px">
            <el-row>
                <!-- 罚款系数 -->
                <el-col :span="8">
                    <el-form-item label="罚款系数">
                        <el-input-number v-model="tempValues.fine_value" :min="0" label="罚款系数"
                            @focus="handleFocus('fine_value')" @blur="handleBlur('fine_value')" />
                    </el-form-item>
                </el-col>
                <el-col :span="4">
                    <el-button type="primary"
                        @click="showConfirmation('fine_value', '确认更新罚款系数吗？', '罚款系数')">确认更新罚款系数</el-button>
                </el-col>
            </el-row>

            <el-row>
                <!-- 锁定天数 -->
                <el-col :span="8">
                    <el-form-item label="锁定期天数">
                        <el-input-number v-model="tempValues.lock_day" :min="0" label="锁定期天数"
                            @focus="handleFocus('lock_day')" @blur="handleBlur('lock_day')" />
                    </el-form-item>
                </el-col>
                <el-col :span="4">
                    <el-button type="primary"
                        @click="showConfirmation('lock_day', '确认更新锁定期天数吗？', '锁定期天数')">确认更新锁定期天数</el-button>
                </el-col>
            </el-row>

            <el-row>
                <!-- 热点期刊征订数量 -->
                <el-col :span="8">
                    <el-form-item label="热点期刊征订数量">
                        <el-input-number v-model="tempValues.num_of_magazine" :min="0" label="热点期刊征订数量"
                            @focus="handleFocus('num_of_magazine')" @blur="handleBlur('num_of_magazine')" />
                    </el-form-item>
                </el-col>
                <el-col :span="4">
                    <el-button type="primary"
                        @click="showConfirmation('num_of_magazine', '确认更新热点期刊征订数量吗？', '热点期刊征订数量')">确认更新热点期刊征订数量</el-button>
                </el-col>
            </el-row>

            <el-row>
                <!-- 学生借阅限制 -->
                <el-col :span="8">
                    <el-form-item label="学生借阅数量上限">
                        <el-input-number v-model="tempValues.NumOfStudentBorrowLimits" :min="0" label="学生借阅数量上限"
                            @focus="handleFocus('NumOfStudentBorrowLimits')"
                            @blur="handleBlur('NumOfStudentBorrowLimits')" />
                    </el-form-item>
                </el-col>
                <el-col :span="4">
                    <el-button type="primary"
                        @click="showConfirmation('NumOfStudentBorrowLimits', '确认更新学生借阅数量上限吗？', '学生借阅数量上限')">确认更新学生借阅数量上限</el-button>
                </el-col>
            </el-row>

            <el-row>
                <!-- 教师借阅限制 -->
                <el-col :span="8">
                    <el-form-item label="教师借阅数量上限">
                        <el-input-number v-model="tempValues.NumOfTeacherBorrowLimits" :min="0" label="教师借阅数量上限"
                            @focus="handleFocus('NumOfTeacherBorrowLimits')"
                            @blur="handleBlur('NumOfTeacherBorrowLimits')" />
                    </el-form-item>
                </el-col>
                <el-col :span="4">
                    <el-button type="primary"
                        @click="showConfirmation('NumOfTeacherBorrowLimits', '确认更新教师借阅数量上限吗？', '教师借阅数量上限')">确认更新教师借阅数量上限</el-button>
                </el-col>
            </el-row>
        </el-form>
    </div>
</template>

<script>
import { ref, onMounted } from "vue";
import { ElMessageBox, ElMessage } from "element-plus";
import { setApi } from "@/request/apiService";

export default {
    setup() {
        const formData = ref({
            fine_value: 0,
            lock_day: 0,
            num_of_magazine: 0,
            NumOfStudentBorrowLimits: 0,
            NumOfTeacherBorrowLimits: 0,
        });

        const tempValues = ref({ ...formData.value });

        // 获取设置数据
        const fetchSettings = async () => {
            try {
                const settings = await setApi.getSettings();
                formData.value = settings;
                tempValues.value = { ...settings };
            } catch (error) {
                ElMessage.error("获取设置失败，请稍后重试！");
            }
        };

        onMounted(fetchSettings);

        // 记录当前输入框的初始值
        const handleFocus = (key) => {
            tempValues.value[key] = formData.value[key];
        };
        const keyLabels = {
            "fine_value": "罚款系数",
            "lock_day": "锁定期天数",
            "num_of_magazine": "热点期刊征订数量",
            "NumOfStudentBorrowLimits": "学生借阅数量上限",
            "NumOfTeacherBorrowLimits": "教师借阅数量上限",
        };

        // 失去焦点时检查是否需要恢复值
        const handleBlur = (key) => {
            if (tempValues.value[key] !== formData.value[key]) {
                let warningMessage = "";
                switch (key) {
                    case "fine_value":
                        warningMessage = "您确定要更新罚款系数吗？";
                        break;
                    case "lock_day":
                        warningMessage = "您确定要更新锁定期天数吗？";
                        break;
                    case "num_of_magazine":
                        warningMessage = "您确定要更新热点期刊征订数量吗？";
                        break;
                    case "NumOfStudentBorrowLimits":
                        warningMessage = "您确定要更新学生借阅数量上限吗？";
                        break;
                    case "NumOfTeacherBorrowLimits":
                        warningMessage = "您确定要更新教师借阅数量上限吗？";
                        break;
                }

                ElMessageBox.confirm(warningMessage, "确认修改", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                })
                    .then(async () => {
                        try {
                            await handleSubmit(key);
                            ElMessage.success(`${keyLabels[key]} 更新成功`);  // 使用中文描述
                        } catch (error) {
                            ElMessage.error(`${keyLabels[key]} 更新失败`);  // 使用中文描述
                        }
                    })
                    .catch(() => {
                        // 恢复原始值
                        tempValues.value[key] = formData.value[key];
                    });
            }
        };


        // 提交更新请求
        const handleSubmit = async (key) => {
            const value = tempValues.value[key];
            try {
                switch (key) {
                    case "fine_value":
                        await setApi.updateFine({ fine_value: value });
                        break;
                    case "lock_day":
                        await setApi.updateLockDay({ lock_day: value });
                        break;
                    case "num_of_magazine":
                        await setApi.updateNumofMagazine({ NumOfMagazine: value });
                        break;
                    case "NumOfStudentBorrowLimits":
                        await setApi.updateStudentBorrowLimits({ NumOfStudentBorrowLimits: value });
                        break;
                    case "NumOfTeacherBorrowLimits":
                        await setApi.updateTeacherBorrowLimits({ NumOfTeacherBorrowLimits: value });
                        break;
                    default:
                        break;
                }
                // 更新成功后，获取最新数据
                fetchSettings();
            } catch (error) {
                ElMessage.error("更新失败，请稍后重试！");
            }
        };

        // 弹出警告框并确认更新
        const showConfirmation = (key, message, label) => {
            ElMessageBox.confirm(message, "确认修改", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
            })
                .then(() => {
                    handleSubmit(key);
                    ElMessage.success(`${label} 更新成功`);
                })
                .catch(() => {
                    // 恢复原始值
                    tempValues.value[key] = formData.value[key];
                });
        };

        return {
            formData,
            tempValues,
            handleFocus,
            handleBlur,
            handleSubmit,
            showConfirmation,
        };
    },
};
</script>

<style scoped>
/* 自定义样式，如果需要 */
</style>